package com.vitech.javacertification.threads.hungrybirds;
class BabyBird extends Thread {
	
	private WormsDish wormDish;
	private MotherBird parent;
	static boolean onlyonce= true;
	
	public BabyBird(WormsDish wormDish, MotherBird parent) {
		this.wormDish = wormDish;
		this.parent = parent;   // the child must know its parent
		if (onlyonce){   // first baby to born start mother tasks
			//this.parent.start();
			onlyonce = false;
			System.out.println("Starting thread Parent");
		}
		
	}
	
	// eating / sleeping thread
	public void run () {
		while (true){		

			if (!wormDish.isEmpty()){
				if ( wormDish.eatWorms () ){   // try to eat
					System.out.println (this.getName()+" eating worm ");
					try {
						
						Thread.yield();
						int sleep = (int) (Math.random () *10000);
						System.out.println(this.getName()+" is sleeping");
						sleep(sleep);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}				
				} else {   // not possible to eat
					System.out.println(this.getName()+" is dead");
					parent.babyStarving(this);  // baby will start crying		
					break;
				}
			}					
		}
	}
}